OOPS INTRODUCTION
Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to design applications and software. These objects are instances of classes, which can hold data in the form of fields (also known as attributes or properties) and code in the form of procedures (also known as methods).
In Java, OOP concepts are the core of the language. Here are the basic principles:
1. Object: An object is an instance of a class and represents a real-world entity. It has a state and behavior. For example, a dog is an object because it has states like color, name, breed, etc., as well as behaviors like wagging the tail, barking, eating, etc.
2. Class: A class is a blueprint from which individual objects are created. It doesn’t consume any space.
Class and method structure
public class Dog {
String breed;
String color;
void bark() {
// code for bark behavior
}
}
3. Inheritance: Inheritance is when an object acquires all the properties and behaviors of a parent object. It provides code reusability.
Inheritance basic structure
public class GermanShepherd extends Dog {
// Inherits all properties and behaviors of Dog class
}
4. Polymorphism: Polymorphism allows one task to be performed in different ways. In Java, we use method overloading and method overriding to achieve polymorphism.
polymorphism basic structure
public class Dog {
void bark() {
// code for bark behavior
}
void bark(String sound) {
// code for bark behavior with specific sound
}
}
5. Abstraction: Abstraction is about hiding internal details and showing functionality.
Abstraction basic structure
abstract class Dog {
abstract void bark();
}
6. Encapsulation: Encapsulation is about binding (or wrapping) code and data together into a single unit.
Encapsulation basic structure
public class Dog {
private String breed;
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
These are the fundamental concepts of OOP in Java. Each of these concepts provides a different way to structure and organize your code.